package com.zhaotianhao.servicestock.controller;

import com.zhaotianhao.servicestock.dao.StockDao;
import com.zhaotianhao.servicestock.dto.OrderDto;
import com.zhaotianhao.servicestock.entity.SkuStock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Z-7
 * @Date 2022/4/28
 */
@Slf4j
@RestController
@RequestMapping("skuStock")
public class SkuStockController {
    @Autowired
    private StockDao stockDao;

    @GetMapping("getStockBySkuId")
    public SkuStock getStockBySkuId(Long skuId){
        SkuStock skuStock = stockDao.findBySkuId(skuId);
        return skuStock;
    }

    /**
     * 生成订单查询对应的库存
     * @param orderDto
     * @return
     */
    @PostMapping("getStockBySkuIds")
    public List<Long> getStockBySkuIds(@RequestBody OrderDto orderDto){
        List<SkuStock> skuStocks = stockDao.findBySkuIdIn(orderDto.getSkuIds());
        List<Long> totalStock = skuStocks.stream().map(a -> a.getTotalStock()).collect(Collectors.toList());
        return totalStock;
    }

    @PostMapping("updateOccupyStock")
    public void updateOccupyStock(@RequestBody SkuStock skuStock) {
        SkuStock findSku = stockDao.findBySkuId(skuStock.getSkuId());
        skuStock.setId(findSku.getId());
        skuStock.setTotalStock(findSku.getTotalStock());
        stockDao.save(skuStock);
        log.info("编号：{}，库存修改成功",skuStock.getId());
    }

    /**
     * 修改库存 传入 skuIds skuNumbers
     * @param orderDto
     * @return 是否成功
     */
    @PostMapping("updateStockBySkuIds")
    public Boolean updateStockBySkuIds(@RequestBody OrderDto orderDto) {
        try {
            List<SkuStock> skuStocks = stockDao.findBySkuIdIn(orderDto.getSkuIds());
            for (int i = 0; i < skuStocks.size(); i++) {
                long totalStock = skuStocks.get(i).getTotalStock() - orderDto.getSkuNumbers().get(i);
                skuStocks.get(i).setTotalStock(totalStock);
            }
            List<SkuStock> list = stockDao.saveAll(skuStocks);
            return list.size() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
